package com.longer.demo.framework.controller;

import com.longer.demo.framework.error.BusinessError;
import com.longer.demo.framework.error.BusinessException;
import com.longer.demo.framework.reponse.CommonResponse;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: demo
 * @description:
 * @author: SunBiaoLong
 * @create: 2019-01-11 13:29
 **/
public class BaseController {
	/**
	 * 常用的contentType类型
	 */
	protected static final String CONTENT_TYPE_FORMED = "application/x-www-form-urlencoded";

	@ExceptionHandler(Exception.class)
	@ResponseStatus(HttpStatus.OK)
	@ResponseBody
	public Object handlerException(Exception ex) {
		Map<String, Object> responseData = new HashMap<>();
		if (ex instanceof BusinessException) {
			responseData.put("errorCode", ((BusinessException) ex).getErrorCode());
			responseData.put("errorMsg", ((BusinessException) ex).getErrorMsg());
		} else {
			responseData.put("errorCode", BusinessError.UNKNOWN_ERROR.getErrorCode());
			responseData.put("errorMsg", BusinessError.UNKNOWN_ERROR.getErrorMsg());
		}

		return CommonResponse.create("fail", responseData);
	}
}
